<template>
  <div>
    <customDialog
      :title="`分配小程序`"
      v-if="dialogVisible"
      :dialogVisible="dialogVisible"
      @close="dialogVisible = false"
      @confirm="confirmDialog"
      width="750"
    >
      <div class="table_box_wrapper">
        <el-transfer
          style="
            display: flex;
            align-items: center;
            justify-content: space-between;
            width: 100%;
          "
          v-loading="loading"
          :data="data"
          v-model="selectedData"
          :titles="['未分配的小程序', '分配的小程序']"
        />
      </div>
    </customDialog>
  </div>
</template>

<script lang="ts" setup>
import customTable from "@/components/CustomTable/index.vue";
import customDialog from "@/components/CustomDialog/index.vue";
import { ref, reactive, toRefs, onMounted, computed } from "vue";
import {
  getBindedAppslist,
  setbindApps,
} from "@/api/operateCenter/distributor/index";
import { getAppOptions } from "@/api/operateCenter/apps/index";
import { debounce } from "lodash-es";

const dialogVisible = ref(false);
const loading = ref(false);
const allocatId = ref();

const data = ref<Array<any>>([]); // 数据源 （未选中）
const selectedData = ref<Array<any>>([]); // 选中

// 绑定
const emit = defineEmits(["success"]);
const confirmDialog = debounce(() => {
  if (!selectedData.value.length)
    return ElMessage.warning("分配的小程序不能为空");
  let params = {
    tenantId: allocatId.value,
    ids: selectedData.value,
  };
  setbindApps(params).then((res) => {
    ElMessage.success("分配成功");
    dialogVisible.value = false;
    emit("success");
  });
}, 150);

// 获取所有小程序
const getNoAllocatApps = () => {
  return getAppOptions({}).then((res: Record<string, any>) => {
    if (!res) return;
    return res?.map((item: Record<string, any>) => {
      item.type = "no";
      return item;
    });
  });
};

// 获取已分配小程序
const getAllocatedApps = () => {
  return getBindedAppslist({ tenantId: allocatId.value }).then(
    (res: Record<string, any>) => {
      return res?.map((item: Record<string, any>) => {
        item.type = "yes";
        return item;
      });
    }
  );
};

const getAllApps = async () => {
  loading.value = true;
  const promise1 = await getAllocatedApps(); // 已分配
  const allApps = await getNoAllocatApps(); // 所有分配

  // console.log("promise111----", promise1);
  // console.log("allApps----", allApps);

  // 等待2个方法执行完成后 再合并两个数据
  Promise.all([promise1, allApps])
    .then((res: any) => {
      loading.value = false;

      // 获取是判断是否有分配好的小程序
      selectedData.value =
        promise1?.map((m: Record<string, any>) => m.id) || [];

      // 替换所有小程序中已分配的id 状态type改为yes
      allApps.map((item: Record<string, any>) => {
        if (selectedData.value.includes(item.id)) {
          item.type = "yes";
        }
      });

      // 将数据格式转化为 穿梭框的数据格式
      data.value = allApps.map((n: Record<string, any>) => {
        return {
          label: `${n.appName} - ${
            n.appType === "wx" ? "微信" : n.appType === "dy" ? "抖音" : ""
          }`,
          key: n.id,
        };
      });

      // console.log("两个方法都执行成功------****------", data.value);
      // console.log("selectedData------****------", selectedData.value);
    })
    .catch((error) => {
      // 处理错误
      console.error("执行方法出错", error);
    });
};

// 父级电子显示dialog
const showDialog = (val: Record<string, any>) => {
  // console.log("---显示分配分销商----**----", val);
  allocatId.value = val?.id;
  dialogVisible.value = true;
  getAllApps();
};

defineExpose({
  showDialog,
});
</script>

<style scoped lang="scss">
.table_box_wrapper {
  :deep(.el-transfer-panel) {
    width: 36%;
  }
}

.form_box {
  padding: 0 20px;
}
</style>
